
/**
 * entity图层
 */
import layerType from '../layerType'
import { v4 as uuid } from 'uuid'
import Layer from '../layer'

export default class EntityLayer extends Layer{
  
  /**
   * 
   * @param {*} viewer viewer场景对象
   * @description 创建图层组 并添加至viewer场景中 代理show 创建对应图层事件
   */

  constructor(viewer){
    super()
    this.id = uuid()
    this._viewer = viewer
    this.collection = new Cesium.CustomDataSource(layerType.ENTITY_LAYER)
    this._show = true
    this._viewer.dataSources.add(this.collection)
  }

  get viewer(){
    return this._viewer
  }

  get show(){
    return this._show
  }

  set show(val){
    this._show = val
    this.collection.show = this._show 
  }

  /**
   * 往集合中增加一个或多个entity元素
   */

  add(entity){
    if(!entity) return
    this._cache[entity.id] = entity
    entity._layer = this
    //触发绑定的事件
    entity.emit()
    this.collection.entities.add(entity.delegate)
  }

  /**
   * 
   * @param {Array} entities 
   */

  adds(entities){
    if(Array.isArray(entities)){
      entities.forEach(entity =>  {
        this.add(entity)
      })
    }
  }

  /**
   * 删除集合中的某个元素
   */
  remove(entity){
    if(!entity) return
    delete this._cache[entity.id]
    entity._layer = undefined
    return this.collection.entities.remove(entity.delegate)
  }

  /**
   * 删除集合中的所有元素
   */

  removeAll(){
    this._cache = {}
    return this.collection.entities.removeAll()
  }

  /**
   * 销毁viewer.datasource中的this
   */
  destroy(){
    this.removeAll()
    this.viewer.dataSources.remove(this.collection)
  }
}